import os

from alipay import AliPay
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django import http

from meiduo_mall.utils.response_code import RETCODE
from orders.models import OrderInfo
from payments.models import Payment


class GetUrlView(View):
    def get(self, request, order_id):
        # 验证订单编号
        try:
            order = OrderInfo.objects.get(pk=order_id)
        except:
            return http.JsonResponse({
                'code': RETCODE.PARAMERR,
                'errmsg': '订单无效',
            })

        # 创建支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/app_private_key.pem'),
            alipay_public_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 生成支付的参数
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='美多商城在-订单支付',
            return_url=settings.ALIPAY_RETURN_URL
        )

        # 拼接最终的支付地址
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        # 响应
        return http.JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'OK',
            'alipay_url': alipay_url
        })


class PaymentStatusView(View):

    def get(self, request):
        '''
        http://www.meiduo.site:8000/payment/status/?charset=utf-8&out_trade_no=20190610150512000000002&method=alipay.trade.page.pay.return&total_amount=27350.00&sign=N2BYToHpzKVnPFmnPhXuL30kYjT7hvkIR9MtsDW1pASsck882uIo13ceGk5KjXdJDQe3K2ZsZew7MQnmXorNZU29sxL47BC5twtA5xmPnKWnyPqhM3mexLeIy2lItQGeymQo2lFNj2%2BfjhBYJD%2Bm92eFpdOg9Dhc%2BbUtUrKO47wgHo9NRny%2BhKGXqyzOX2uEBiVDJL10jeIF1DUzaH%2BZBfAkL3PMaj3c8gzC5Ig3zjTSJsTY9t2fHPSAcodJnt%2BP%2BmHfGlS8WokO5p0ao9WnNGK3aJAg60EYGtQmdTZ5iBE%2BbSSyzY%2BnaZGiqWswJPk1pHhcJZcQWBPQZ6b8NJIhDg%3D%3D&trade_no=2019061122001417701000021261&auth_app_id=2016092800618170&version=1.0&app_id=2016092800618170&sign_type=RSA2&seller_id=2088102177696175&timestamp=2019-06-11+00%3A27%3A09
        '''
        # 获取前端传入的请求参数
        query_dict = request.GET
        data = query_dict.dict()
        # 获取并从请求参数中剔除signature
        signature = data.pop('sign')

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/app_private_key.pem'),
            alipay_public_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data, signature)
        if success:
            # 读取order_id
            order_id = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_id = data.get('trade_no')

            try:
                # 保存Payment模型类数据
                Payment.objects.create(
                    order_id=order_id,
                    trade_id=trade_id
                )
            except:
                return http.HttpResponseForbidden('非法请求')

            # 修改订单状态为待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNCOMMENT"])

            # 响应trade_id
            context = {
                'trade_id': trade_id
            }
            return render(request, 'pay_success.html', context)
        else:
            # 订单支付失败，重定向到我的订单
            return http.HttpResponseForbidden('非法请求')
